<?php

namespace framework\support;

class Request
{
    private  $data = [];
    private $headers = [];


    public  function data($name, $value = null)
    {
        if ($value) {
            $this->data[$name] = $value;
        } else {
            return $this->data[$name] ?? null;
        }
    }

    public  function get($name = null, $default = null)
    {
        if (!$name) {
            return $_GET;
        } else {
            return $_GET[$name] ?? $default;
        }
    }

    public  function server($name = null, $default = null)
    {
        if (!$name) {
            return $_SERVER;
        } else {
            return $_SERVER[$name] ?? $default;
        }
    }

    public  function post($name = null, $default = null)
    {
        if (!$name) {
            return $_POST;
        } else {
            return $_POST[$name] ?? $default;
        }
    }


    public  function file($name)
    {
        return $_File[$name] ?? null;
    }

    public  function header($name)
    {
        if (!$this->headers) {
            $this->headers = getallheaders();
        }

        return $this->headers[$name] ?? null;
    }

    public  function rawBody()
    {
        return file_get_contents("php://input");
    }

    function getRealIp()
    {
        // 检查是否存在代理服务器
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            // 处理多个 IP 地址的情况
            $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $ip = trim($ips[0]);
        } elseif (isset($_SERVER['HTTP_X_REAL_IP'])) {
            $ip = $_SERVER['HTTP_X_REAL_IP'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    /**
     * 判断当前请求是否为 AJAX 请求
     *
     * @return bool 如果是 AJAX 请求返回 true，否则返回 false
     */
    public function isAjax()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }
}
